package com.zzy.database.controller;

import com.zzy.database.pojo.Customer;
import com.zzy.database.pojo.Result;
import com.zzy.database.service.CustomerService;
import com.zzy.database.utils.JsonUtil;
import com.zzy.database.utils.Jwtutil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/customers")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @PostMapping
    public Result addCustomer(@RequestBody Customer customer) {
        try {
            customer.setCustomer_id(UUID.randomUUID().toString());
            customerService.addCustomer(customer);

            return Result.success("添加成功");
        }catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @PutMapping
    public Result updateCustomer(@RequestBody Customer customer) {
        try{
            customerService.updateCustomer(customer);
            return Result.success(customer);
        }catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @DeleteMapping
    public Result deleteCustomerById(@RequestBody Customer customer) {
        try{
            customerService.deleteCustomerById(customer.getCustomer_id());
            return Result.success();
        }catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }

    }

    @GetMapping("/getById")
    public Result getCustomerById(@RequestBody Customer customer) {
        Customer result = customerService.getCustomerById(customer.getCustomer_id());
        log.info(result.getCustomer_id());
        if (result == null) {
            return Result.error("用户不存在");
        }else {
            return Result.success(result);
        }
    }

    @GetMapping("/getAll")
    public Result getAllCustomers() {
        List<Customer> customerList = customerService.getAllCustomers();
        return Result.success(customerList);
    }
    @PostMapping("/completeCustomer")
    public Result complteCustomer(@RequestBody Customer customer,@RequestHeader("Authorization") String authorization){

        Map<String, Object> map = Jwtutil.parseToken(authorization);
        String username = (String) map.get("username");
        String userid=(String)map.get("id");
        customer.setCustomer_id(userid);
        customer.setUser_name(username);
        customerService.complete(customer);
        return Result.success();
    }
}
